<?php 
class Calendar {
	/**
	 * Given a year and a month it returns a matrix (nx7) formed as follow:
	 * 			First row 			<- name of day
	 * 			Second to n-th row	<- num of day in the usual calendar view
	 */
	
	public function generateCalendar($year = -1, $month = -1, $day_name_length = 3) {
		$calendar = array();
		$row = 0;

		if($year==-1) {
			$year = date("Y", time());
		}
		if($month==-1) {
			$month = date("m", time());
		}
		// UNIX timestamp of the first day of the month
		$first_of_month = mktime(0, 0, 0, $month, 1, $year);
		
		$calendar[$row] = array();
		for($n=0, $t=3*86400; $n<7; $n++, $t+=86400) {
			$d = strftime("%A", $t);
			$calendar[$row][] = substr($d, 0, $day_name_length);
		}

		$weekday = date("w", $first_of_month);
		$row++;
		$calendar[$row] = array();
		if($weekday>0) {
			do {
				$calendar[$row][] = NULL;
				$weekday--;
			} while($weekday>0);
		}
		$days_in_month = date("t", $first_of_month);
		$weekday = count($calendar[$row]);
		for($day=1; $day<=$days_in_month; $day++, $weekday++) {
			if($weekday==7) { 
				$weekday = 0;
				$row++;
				$calendar[$row] = array();
			} 
			$calendar[$row][] = $day;
		}
		if($weekday!=7) {
			do {
				$calendar[$row][] = NULL;
				$weekday++;
			} while($weekday<7);
		}

		return $calendar; 
	}
}
?>